import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import '../../core/constants.dart';
import '../../shared/models/word.dart';
import '../../shared/providers/word_provider.dart';
import 'word_detail_page.dart';

class WordListPage extends ConsumerWidget {
  final String category;
  final String? searchQuery;

  const WordListPage({
    super.key,
    required this.category,
    this.searchQuery,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final AsyncValue<List<Word>> wordsAsync = searchQuery != null
        ? ref.watch(searchWordsProvider(searchQuery!))
        : category == WordCategories.STARRED
            ? ref.watch(_favoriteWordsListProvider)
            : ref.watch(wordsProvider(category));

    // Determine the hero tag and colors based on category
    String heroTag = 'vocabulary_learning_hero';
    Color primaryColor = AppConstants.PRIMARY_BLUE;
    Color secondaryColor = AppConstants.DARK_BLUE;
    
    if (category == WordCategories.STARRED) {
      heroTag = 'starred_words_hero';
      primaryColor = Colors.amber.shade600;
      secondaryColor = Colors.amber.shade700;
    }

    return Scaffold(
      appBar: AppBar(
        title: Text(category),
        centerTitle: true,
        elevation: 0,
        backgroundColor: primaryColor,
        foregroundColor: Colors.white,
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                primaryColor,
                secondaryColor,
              ],
            ),
          ),
        ),
        leading: Container(
          margin: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: Colors.white.withOpacity(0.1),
            borderRadius: BorderRadius.circular(12),
          ),
          child: IconButton(
            icon: const FaIcon(
              FontAwesomeIcons.arrowLeft,
              color: Colors.white,
              size: 18,
            ),
            onPressed: () => Navigator.pop(context),
          ),
        ),
      ),
      body: GestureDetector(
        onTap: () {
          // Dismiss keyboard when tapping outside
          FocusManager.instance.primaryFocus?.unfocus();
        },
        child: wordsAsync.when(
          data: (words) => _buildWordsList(context, ref, words),
          loading: () => const Center(child: CircularProgressIndicator()),
          error: (error, stack) => Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.error_outline,
                  size: 64,
                  color: Colors.grey[400],
                ),
                const SizedBox(height: 16),
                Text(
                  'Error loading words',
                  style: TextStyle(
                    fontSize: 18,
                    color: Colors.grey[600],
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  error.toString(),
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[500],
                  ),
                  textAlign: TextAlign.center,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildWordsList(BuildContext context, WidgetRef ref, List<Word> words) {
    if (words.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.search_off,
              size: 64,
              color: Colors.grey[400],
            ),
            const SizedBox(height: 16),
            Text(
              'No words found',
              style: TextStyle(
                fontSize: 18,
                color: Colors.grey[600],
              ),
            ),
            const SizedBox(height: 8),
            Text(
              searchQuery != null
                  ? 'Try a different search term'
                  : 'No words available in this category',
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[500],
              ),
            ),
          ],
        ),
      );
    }

    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: words.length,
      itemBuilder: (context, index) {
        final word = words[index];
        return _buildWordCard(context, ref, word);
      },
    );
  }

  Widget _buildWordCard(BuildContext context, WidgetRef ref, Word word) {
    final favoriteWords = ref.watch(favoriteWordsProvider);
    final isFavorite = favoriteWords.contains(word.id);

    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 5,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: ListTile(
        contentPadding: const EdgeInsets.all(16),
        title: Row(
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    word.esperanto,
                    style: const TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: AppConstants.DARK_BLUE,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    word.english,
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.grey[600],
                    ),
                  ),
                ],
              ),
            ),
            IconButton(
              onPressed: () {
                ref.read(favoriteWordsProvider.notifier).toggleFavorite(word.id);
              },
              icon: FaIcon(
                isFavorite ? FontAwesomeIcons.solidStar : FontAwesomeIcons.star,
                color: isFavorite ? Colors.amber : Colors.grey,
                size: 18,
              ),
            ),
          ],
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 8),
            Text(
              word.pronunciation,
              style: TextStyle(
                fontSize: 14,
                fontStyle: FontStyle.italic,
                color: Colors.grey[500],
              ),
            ),
            const SizedBox(height: 4),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: AppConstants.PRIMARY_BLUE.withOpacity(0.1),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Text(
                word.category,
                style: const TextStyle(
                  fontSize: 12,
                  color: AppConstants.PRIMARY_BLUE,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ],
        ),
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => WordDetailPage(wordId: word.id),
            ),
          );
        },
      ),
    );
  }
}

final _favoriteWordsListProvider = FutureProvider<List<Word>>((ref) async {
  final favoriteIds = ref.watch(favoriteWordsProvider);
  final wordService = ref.watch(wordServiceProvider);
  
  final List<Word> favoriteWords = [];
  for (final id in favoriteIds) {
    final word = await wordService.getWordById(id);
    if (word != null) {
      favoriteWords.add(word);
    }
  }
  
  return favoriteWords;
}); 